package com.silong.util;

import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.JavaType;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * Created by zz on 2016/7/5.
 */
public class JsonrUtils {

    private static ObjectMapper objectMapper = null;

    /**
     *
     * @param json
     * @param valueType
     * @param <T>
     * @return
     */
    public static <T> T readJson2Entity(String json,Class<T> valueType) {

        try {
            objectMapper=new ObjectMapper();
            objectMapper.configure(DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
            return objectMapper.readValue(json, valueType);

        } catch (JsonParseException e) {

            e.printStackTrace();

        }catch (IOException e) {

            e.printStackTrace();

        }
        return  null;
    }
    /**
     * json数组转List
     * @param jsonStr
     * @param obj
     * @return
     */
    public static <T> T readValue(String jsonStr,Class<?> obj){

            objectMapper = new ObjectMapper();
        JavaType javaType =  objectMapper.getTypeFactory().constructParametricType(List.class,obj);
        objectMapper.configure(DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
        try {
            return objectMapper.readValue(jsonStr, javaType);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 把JavaBean转换为json字符串
     *
     * @param object
     * @return
     */
    public static String toJSon(Object object) {
            objectMapper = new ObjectMapper();
        try {
            return objectMapper.writeValueAsString(object);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * jsonString 转Map
     * @param json
     * @return
     */
    public static Map  readToMap(String json){
        //json字符串转为Map对象
        objectMapper=new ObjectMapper();

        try {
          return objectMapper.readValue(json, Map.class);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

}
